package org.zhiyootech.utils;

import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.jboss.logging.Logger;

import java.util.HashMap;
import java.util.Map;

public final class JsonUtils {

    private static final Logger logger = Logger.getLogger(JsonUtils.class);


    private static final ObjectMapper MAPPER = new ObjectMapper();

    private JsonUtils() {
    }

    public static ObjectMapper getObjectMapperInstance() {
        return MAPPER;
    }

    public static boolean isNullJsonNode(JsonNode node) {
        return node == null || StringUtils.equals(node.toString(), "null");
    }

    public static String toJsonString(Object obj) {
        try {
            return MAPPER.writeValueAsString(obj);
        } catch (Exception var2) {
            logger.error("JsonUtils.toJsonString error, exception = {}", var2);
        }
        return null;
    }

    public static <T> T toBean(String json, Class<T> cls) {
        try {
            return MAPPER.readValue(json, cls);
        } catch (Exception var3) {
            logger.error("JsonUtils.toBean error, exception = {}", var3);
        }
        return null;
    }

    public static <T> T toBean(String json, TypeReference<T> type) {
        try {
            return MAPPER.readValue(json, type);
        } catch (Exception var3) {
            logger.error("JsonUtils.toBean error, exception = {}", var3);
        }
        return null;
    }

    /**
     * 将对象序列化为Json串
     *
     * @param o 被序列化对象
     * @return null if o == null
     */
    public static String read(Object o) {
        return o == null ? null : toJsonString(o);
    }

    public static Map<Object, Object> write(String json) {
        return write(json, HashMap.class);
    }

    /**
     * 将Json串反序列化成对象
     *
     * @param json  Json串
     * @param clazz 对象类型
     * @param <T>
     * @return null if json is empty
     */
    public static <T> T write(String json, Class<T> clazz) {
        if (StringUtils.isNotEmpty(json)) {
            return toBean(json, clazz);
        }
        return null;
    }

    static {
        MAPPER.configure(Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
        MAPPER.configure(Feature.ALLOW_COMMENTS, true);
        MAPPER.configure(Feature.ALLOW_NON_NUMERIC_NUMBERS, true);
        MAPPER.configure(Feature.ALLOW_NUMERIC_LEADING_ZEROS, true);
        MAPPER.configure(Feature.ALLOW_SINGLE_QUOTES, true);
        MAPPER.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
        MAPPER.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
}
